﻿using AntdUI; // UI库 https://gitee.com/AntdUI/AntdUI
using AutoScaleHelper; // 自动缩放库
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Resources;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using static MMD_Morph_NoteHelp.MainForm;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
using ToolTip = System.Windows.Forms.ToolTip; // 消息悬停

namespace MMD_Morph_NoteHelp
{
    // ===================== 
    //    表情预设库
    // =====================
    public partial class PresetForm : AntdUI.Window
    {
        private MainForm mainForm; // 主窗体引用

        private ControlMonitorService _monitorService;
        private PresetFile _selectedPresetFile = null;
        private ToolTip toolTip1 = new ToolTip(); // 悬停提示实例
        private string _currentFolderPath; // 记忆预设文件夹路径
        private CancellationTokenSource _cancellationTokenSource; // 取消令牌源

        // 语言资源文件
        private ResourceManager resManager = new ResourceManager("MMD_Morph_NoteHelp.LanguageList.Resource", typeof(OptionWin).Assembly);

        public PresetForm(ControlMonitorService monitorService)
        {
            InitializeComponent();
            this.StartPosition = FormStartPosition.CenterParent; // 窗口居中显示
            //this.Mode = AntdUI.TAMode.Light; // 确保窗口始终为浅色模式
            ThemeManager.OnThemeChanged += ApplyThemeColors; // 订阅主题更改事件
            _monitorService = monitorService;

            TablePresetsList.DisplayMember = "FileName";

            // 悬停提示
            toolTip1.SetToolTip(PresetLoadFolderButton, "打开文件夹");
            toolTip1.SetToolTip(PresetApplyButton, "应用预设");
            toolTip1.SetToolTip(StopWork, "暂停任务");
            toolTip1.SetToolTip(PresetDeleteButton, "删除预设");

            ApplyLocalization(); // 确保语言更新

            // 由于不需要txt预设文件了，隐藏应用按钮
            StopWork.Dispose();
        }

        private void PresetForm_Shown(object sender, EventArgs e)
        {
            // 在窗口显示时，加载默认路径
            _currentFolderPath = GetDefaultPresetPath();
            // 把路径显示到输入框
            FolderPathLink.Text = _currentFolderPath; 
            LoadPresetsFromFolder(_currentFolderPath); // 记忆路径
            // 根据当前主题应用颜色
            ApplyThemeColors(ThemeManager.IsDark);
        }

        // 根据主题应用颜色
        public void ApplyThemeColors(bool isDark)
        {
            this.Mode = isDark ? AntdUI.TAMode.Dark : AntdUI.TAMode.Light;
            if (isDark) // 深色模式
            {
                this.BackColor = Color.FromArgb(48, 48, 48); // 预设窗口背景
                PresetHeader.BackColor = Color.FromArgb(64, 64, 64); // 标题栏背景
                PresetHeader.ForeColor = Color.White; // 标题栏文字
                FolderPathLink.BackColor = Color.FromArgb(48, 48, 48); // 路径输入框背景
                FolderPathLink.ForeColor = Color.White; // 路径输入框文字
                TablePresetsList.BackColor = Color.FromArgb(48, 48, 48); // 列表背景
                TablePresetsList.ForeColor = Color.White; // 列表文字
                PresetLoadFolderButton.BackColor = Color.FromArgb(48, 48, 48); // 打开文件夹按钮背景
                PresetLoadFolderButton.ForeColor = Color.White; // 打开文件夹按钮文字
                PresetApplyButton.BackColor = Color.FromArgb(48, 48, 48); // 应用按钮背景
                PresetApplyButton.ForeColor = Color.White; // 应用按钮文字
                StopWork.BackColor = Color.FromArgb(48, 48, 48); // 终止按钮背景
                StopWork.ForeColor = Color.White; // 终止按钮文字
                PresetDeleteButton.BackColor = Color.FromArgb(48, 48, 48); // 删除按钮背景
                PresetDeleteButton.ForeColor = Color.White; // 删除按钮文字
            }
            else // 浅色模式
            {
                this.BackColor = SystemColors.Control; // 预设窗口背景
                PresetHeader.BackColor = SystemColors.Window; // 标题栏背景
                PresetHeader.ForeColor = SystemColors.WindowText; // 标题栏文字
                FolderPathLink.BackColor = SystemColors.Window; // 路径输入框背景
                FolderPathLink.ForeColor = SystemColors.WindowText; // 路径输入框文字
                TablePresetsList.BackColor = SystemColors.Window; // 列表背景
                TablePresetsList.ForeColor = SystemColors.WindowText; // 列表文字
                PresetLoadFolderButton.BackColor = SystemColors.Window; // 打开文件夹按钮背景
                PresetLoadFolderButton.ForeColor = SystemColors.WindowText; // 打开文件夹按钮文字
                PresetApplyButton.BackColor = SystemColors.Window; // 应用按钮背景
                PresetApplyButton.ForeColor = SystemColors.WindowText; // 应用按钮文字
                StopWork.BackColor = SystemColors.Window; // 终止按钮背景
                StopWork.ForeColor = SystemColors.WindowText; // 终止按钮文字
                PresetDeleteButton.BackColor = SystemColors.Window; // 删除按钮背景
                PresetDeleteButton.ForeColor = SystemColors.WindowText; // 删除按钮文字
            }
            this.Refresh();
        }

        // 窗口关闭时，取消订阅事件
        protected override void OnFormClosing(FormClosingEventArgs e)
        {
            ThemeManager.OnThemeChanged -= ApplyThemeColors; // 取消订阅主题更改事件
            base.OnFormClosing(e);
        }

        // 获取默认预设文件夹路径
        private string GetDefaultPresetPath()
        {
            string path = Path.Combine(Application.StartupPath, "Presets"); // 默认预设文件夹
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            return path;
        }

        // 从指定文件夹加载预设文件
        private void LoadPresetsFromFolder(string folderPath)
        {
            _selectedPresetFile = null;
            var presetFiles = new List<PresetFile>();

            if (Directory.Exists(folderPath))
            {   
                // 移除.txt文件，因为可能导致电脑性能不同无法成功，还是采用vmd方式稳妥
                // var files = Directory.GetFiles(folderPath, "*.txt")
                //     .Concat(Directory.GetFiles(folderPath, "*.vmd"));
                var files = Directory.GetFiles(folderPath, "*.vmd");
                foreach (var file in files)
                {
                    presetFiles.Add(new PresetFile
                    {
                        FileName = Path.GetFileName(file),
                        FullPath = file
                    });
                }
            }

            // 强制表格刷新数据
            TablePresetsList.DataSource = null; // 先清空旧数据源
            TablePresetsList.DataSource = presetFiles; // 再设置新数据源
        }

        // 列表点击事件
        // 要显示滚动条，需到设计器里把ListBox控件的垂直滚动条ScrollAlwaysVisible设为True，水平滚动条HorizontalScrollbar设为True
        private void TablePresetsList_SelectedIndexChanged(object sender, EventArgs e)
        {
            // 当选中项改变时，更新我们跟踪的变量
            // ListBox.SelectedItem 会直接返回我们绑定的那个 PresetFile 对象
            if (TablePresetsList.SelectedItem is PresetFile selected)
            {
                _selectedPresetFile = selected;
            }
        }

        // 打开文件夹按钮
        private void PresetLoadFolderButton_Click(object sender, EventArgs e)
        {
            using (var fbd = new System.Windows.Forms.FolderBrowserDialog())
            {
                fbd.SelectedPath = _currentFolderPath; // 记忆上次打开的文件夹
                DialogResult result = fbd.ShowDialog(this); // 加上this，居中显示
                if (result == DialogResult.OK && !string.IsNullOrWhiteSpace(fbd.SelectedPath))
                {
                    // === 更新记忆 ===
                    _currentFolderPath = fbd.SelectedPath;
                    FolderPathLink.Text = _currentFolderPath;
                    LoadPresetsFromFolder(_currentFolderPath);
                }
            }
        }

        // 应用按钮
        private async void PresetApplyButton_Click(object sender, EventArgs e)
        {
            if (_selectedPresetFile == null)
            {
                // MessageBox.Show("请先在列表中选择一个预设。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                MessageBox.Show(this, L10n.Get("Info_SelectPreset_Body"), L10n.Get("Info_NoDataToSave_Title"), MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            string filePath = _selectedPresetFile.FullPath; // 完整路径

            // 根据文件类型，执行不同的命令

            // ----------------------
            //    txt预设文件
            // ----------------------
            if (filePath.EndsWith(".txt", StringComparison.OrdinalIgnoreCase))
            {
                try
                {
                    // 读取预设文件内容
                    string[] lines = File.ReadAllLines(filePath, Encoding.UTF8);
                    var dataToApply = new MorphData();
                    dataToApply.ModelName = lines[0].Replace("name:", "").Trim();
                    for (int i = 2; i < lines.Length; i++)
                    {
                        string line = lines[i];
                        if (string.IsNullOrWhiteSpace(line)) continue;
                        var parts = line.Split(new[] { ':' }, 2);
                        if (parts.Length == 2)
                        {
                            dataToApply.Morphs[parts[0].Trim()] = parts[1].Trim();
                        }
                    }

                    // 把更新标题的逻辑也传进去
                    Action<int, int> progressCallback = (current, total) =>
                    {
                        this.Text = L10n.Get("PresetForm_ApplyingProgress_Text", (int)(((double)current / total) * 100)); // this.Text = $"正在应用预设 ({(int)(((double)current / total) * 100)}%) ...";

                    };

                    this.Text = L10n.Get("PresetForm_Applying_Text"); // "正在应用预设...
                    PresetApplyButton.Enabled = false; // 禁用“应用”按钮
                    StopWork.Enabled = true; // 激活“终止”按钮

                    // 创建取消令牌源
                    _cancellationTokenSource = new CancellationTokenSource();
                    // 传递给核心任务！
                    List<string> failed = await _monitorService.ApplyMorphData(dataToApply, progressCallback, _cancellationTokenSource.Token);

                    // 根据结果显示不同的消息
                    if (failed.Count == 0)
                    {
                        MessageBox.Show(this, L10n.Get("Info_ApplySuccess_Body"), L10n.Get("Info_ApplySuccess_Title"), MessageBoxButtons.OK, MessageBoxIcon.Information); // 预设已成功应用！
                    }
                    else
                    {
                        // MessageBox.Show(this,$"部分表情应用失败，可能是在当前模型中不存在：\n\n{string.Join("\n", failed)}", "部分成功", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        string failedMorphsList = string.Join("\n", failed);
                        MessageBox.Show(this, L10n.Get("Warning_ApplyPartial_Body", failedMorphsList), L10n.Get("Warning_ApplyPartial_Title"), MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                }
                // 捕获任务取消异常
                catch (OperationCanceledException)
                {
                    // 如果任务是因为按了“终止”而被取消的，就会捕获到这个异常
                    MessageBox.Show(this, L10n.Get("Task_cancelled_Body"), L10n.Get("Task_cancelled_Title"), MessageBoxButtons.OK, MessageBoxIcon.Warning); // 任务已被终止。
                }
                // 捕捉错误异常
                catch (Exception ex)
                {
                    // MessageBox.Show(this, $"加载或应用预设时发生错误：\n{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    MessageBox.Show(L10n.Get("Error_ApplyFailed_Body", ex.Message), L10n.Get("Error_ApplyFailed_Title"), MessageBoxButtons.OK, MessageBoxIcon.Error);
                    this.Text = L10n.Get("PresetForm_Title"); // 表情预设库
                    PresetApplyButton.Enabled = true;
                }
                // 完成后
                finally
                {
                    // === 任务完成，恢复按钮状态 ===
                    this.Text = L10n.Get("PresetForm_Title"); // 表情预设库
                    PresetApplyButton.Enabled = true; // 恢复“应用”按钮
                    StopWork.Enabled = false; // 禁用“终止”按钮
                }
            }
            // ----------------------
            //    vmd预设文件
            // ----------------------
            else if (filePath.EndsWith(".vmd", StringComparison.OrdinalIgnoreCase))
            {
                try
                {
                    this.Text = L10n.Get("importVMDLoad"); // 正在导入 .vmd文件 ...
                    PresetApplyButton.Enabled = false; // 禁用“应用”按钮
                    StopWork.Enabled = true; // 激活“终止”按钮

                    await Win32Helper.ImportVMDWithAHK(filePath); // 调用AHK脚本传入完整路径

                    MessageBox.Show(this, L10n.Get("VMDFileSent"), L10n.Get("Operationcompleted_Title"), MessageBoxButtons.OK, MessageBoxIcon.Information);
                    // MessageBox.Show(this, "vmd文件已成功导入！", "导入完成", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                catch (Exception ex)
                {
                    // MessageBox.Show(this, $"导入 .vmd 时发生错误：\n{ex.Message}", "导入失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    MessageBox.Show(L10n.Get("VMDImportError", ex.Message), L10n.Get("VMDImportFailed"), MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                finally
                {   // === 任务完成，恢复按钮状态 ===
                    this.Text = L10n.Get("PresetForm_Title"); // 表情预设库
                    PresetApplyButton.Enabled = true; // 恢复“应用”按钮
                    StopWork.Enabled = false; // 禁用“终止”按钮
                }
            }
        }

        // 强行终止任务按钮
        private void StopWork_Click(object sender, EventArgs e)
        {
            _cancellationTokenSource?.Cancel(); // 终止任务事件
        }

        // 删除按钮
        private void PresetDeleteButton_Click(object sender, EventArgs e)
        {
            if (_selectedPresetFile == null) return;

            string filePath = _selectedPresetFile.FullPath; // 完整路径
            string fileName = _selectedPresetFile.FileName; // 文件名

            // var confirmResult = MessageBox.Show($"确定要删除预设 '{fileName}' 吗？\n该操作无法撤销。", "确认删除", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
            var confirmResult = MessageBox.Show(L10n.Get("Confirm_Delete_Body", fileName), L10n.Get("Confirm_Delete_Title"), MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
            if (confirmResult == DialogResult.Yes)
            {
                try
                {
                    File.Delete(filePath);
                    LoadPresetsFromFolder(_currentFolderPath); // 记忆路径判断
                }
                catch (Exception ex)
                {
                   // MessageBox.Show($"删除文件时出错：\n{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    MessageBox.Show(L10n.Get("Error_DeleteFailed_Body", ex.Message), L10n.Get("Error_ApplyFailed_Title"), MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

        // 多语言
        public void ApplyLocalization()
        {
            PresetHeader.Text = resManager.GetString("PresetHeader_Title", Thread.CurrentThread.CurrentUICulture); // 表情预设标题
            toolTip1.SetToolTip(PresetLoadFolderButton, resManager.GetString("PresetLoadFolderButton_ToolTip", Thread.CurrentThread.CurrentUICulture)); // 打开文件夹提示文字
            toolTip1.SetToolTip(PresetApplyButton, resManager.GetString("PresetApplyButton_ToolTip", Thread.CurrentThread.CurrentUICulture)); // 应用预设
            toolTip1.SetToolTip(StopWork, resManager.GetString("StopWorkButton_ToolTip", Thread.CurrentThread.CurrentUICulture)); // 暂停任务
            toolTip1.SetToolTip(PresetDeleteButton, resManager.GetString("PresetDeleteButton_ToolTip", Thread.CurrentThread.CurrentUICulture)); // 删除预设
        }

        public class PresetFile
        {
            public string FileName { get; set; }
            public string FullPath { get; set; }
            public override string ToString()
            {
                return FileName; // 文本字符串
            }
        }


        // ========= END ==============
    }
}